<template>
  <div class="admin-panel">
    <div class="container">
      <div class="admin-header">
        <h1 class="page-title">管理员控制台</h1>
        <p class="page-description">
          系统管理和数据统计
        </p>
      </div>

      <div class="admin-content">
        <!-- 统计卡片 -->
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon">
              <Users :size="32" />
            </div>
            <div class="stat-info">
              <h3>{{ totalUsers }}</h3>
              <p>总用户数</p>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon">
              <BookOpen :size="32" />
            </div>
            <div class="stat-info">
              <h3>{{ totalStories }}</h3>
              <p>总故事数</p>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon">
              <Eye :size="32" />
            </div>
            <div class="stat-info">
              <h3>{{ totalViews }}</h3>
              <p>总浏览量</p>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon">
              <Heart :size="32" />
            </div>
            <div class="stat-info">
              <h3>{{ totalLikes }}</h3>
              <p>总点赞数</p>
            </div>
          </div>
        </div>

        <!-- 数据可视化分析 -->
        <div class="analytics-section" v-if="analyticsData">
          <div class="section-header-main">
            <h2>📊 数据可视化分析</h2>
            <button @click="loadAnalytics" class="btn btn-secondary btn-sm">
              <RefreshCw :size="16" />
              刷新数据
            </button>
          </div>

          <!-- 图表网格 -->
          <div class="charts-grid">
            <!-- 故事创建趋势 -->
            <ChartCard
              title="故事创建趋势"
              description="最近7天的故事创建数量"
              chart-id="dailyStoriesChart"
              type="line"
              :data="dailyStoriesChartData"
            />

            <!-- 用户注册趋势 -->
            <ChartCard
              title="用户注册趋势"
              description="最近7天的用户注册数量"
              chart-id="dailyUsersChart"
              type="line"
              :data="dailyUsersChartData"
            />

            <!-- 故事状态分布 -->
            <ChartCard
              title="故事状态分布"
              description="已发布 vs 草稿"
              chart-id="statusChart"
              type="doughnut"
              :data="statusChartData"
            />

            <!-- 审核状态分布 -->
            <ChartCard
              title="审核状态分布"
              description="待审核、已通过、已驳回"
              chart-id="reviewChart"
              type="pie"
              :data="reviewChartData"
            />

            <!-- 分类分布 -->
            <ChartCard
              title="故事分类分布"
              description="各类型故事数量统计"
              chart-id="categoryChart"
              type="bar"
              :data="categoryChartData"
              class="chart-wide"
            />

            <!-- 热门作者 -->
            <ChartCard
              title="热门作者排行"
              description="按故事数量排序"
              chart-id="authorsChart"
              type="bar"
              :data="authorsChartData"
              class="chart-wide"
            />
          </div>

          <!-- 热门故事表格 -->
          <div class="top-stories-section">
            <h3>🔥 热门故事 Top 5</h3>
            <div class="data-table">
              <table>
                <thead>
                  <tr>
                    <th>排名</th>
                    <th>标题</th>
                    <th>作者</th>
                    <th>浏览量</th>
                    <th>点赞数</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(story, index) in analyticsData.top_stories" :key="story.id">
                    <td>
                      <span class="rank-badge" :class="'rank-' + (index + 1)">{{ index + 1 }}</span>
                    </td>
                    <td class="story-title">{{ story.title }}</td>
                    <td>{{ story.author }}</td>
                    <td>
                      <span class="metric-badge views">{{ story.views }}</span>
                    </td>
                    <td>
                      <span class="metric-badge likes">{{ story.likes }}</span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- 管理功能区 -->
        <div class="admin-sections">
          <!-- 用户管理 -->
          <div class="admin-section">
            <div class="section-header">
              <h2>用户管理</h2>
              <button @click="refreshUsers" class="btn btn-secondary btn-sm">
                <RefreshCw :size="16" />
                刷新
              </button>
            </div>

            <div class="data-table">
              <table>
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>邮箱</th>
                    <th>角色</th>
                    <th>注册时间</th>
                    <th>故事数</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="user in users" :key="user.id">
                    <td>{{ user.id }}</td>
                    <td>{{ user.name }}</td>
                    <td>{{ user.email }}</td>
                    <td>
                      <span class="role-badge" :class="user.role">
                        {{ getRoleText(user.role) }}
                      </span>
                    </td>
                    <td>{{ formatDate(user.joinDate) }}</td>
                    <td>{{ user.storiesCount || 0 }}</td>
                    <td>
                      <button 
                        @click="toggleUserRole(user)" 
                        class="btn btn-ghost btn-xs"
                        :disabled="user.id === authStore.currentUser?.id"
                      >
                        切换角色
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- 故事管理 -->
          <div class="admin-section">
            <div class="section-header">
              <h2>故事管理</h2>
              <div class="header-actions">
                <select v-model="reviewFilter" class="filter-select">
                  <option value="all">全部</option>
                  <option value="pending">待审核</option>
                  <option value="approved">已通过</option>
                  <option value="rejected">已驳回</option>
                </select>
                <button @click="refreshStories" class="btn btn-secondary btn-sm">
                  <RefreshCw :size="16" />
                  刷新
                </button>
              </div>
            </div>

            <div class="data-table">
              <table>
                <thead>
                  <tr>
                    <th>
                      <input 
                        type="checkbox" 
                        @change="toggleSelectAll" 
                        :checked="allSelected"
                      />
                    </th>
                    <th>ID</th>
                    <th>标题</th>
                    <th>作者</th>
                    <th>分类</th>
                    <th>状态</th>
                    <th>审核状态</th>
                    <th>创建时间</th>
                    <th>浏览量</th>
                    <th>点赞数</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="story in filteredStories" :key="story.id">
                    <td>
                      <input 
                        type="checkbox" 
                        v-model="selectedStories" 
                        :value="story.id"
                      />
                    </td>
                    <td>{{ story.id }}</td>
                    <td class="story-title">{{ story.title }}</td>
                    <td>{{ story.author_name || story.author }}</td>
                    <td>
                      <span class="category-badge">{{ story.category }}</span>
                    </td>
                    <td>
                      <span class="status-badge" :class="story.status">
                        {{ getStatusText(story.status) }}
                      </span>
                    </td>
                    <td>
                      <span class="review-badge" :class="story.review_status">
                        {{ getReviewStatusText(story.review_status) }}
                      </span>
                    </td>
                    <td>{{ formatDate(story.created_at || story.createdAt) }}</td>
                    <td>{{ story.views || 0 }}</td>
                    <td>{{ story.likes || 0 }}</td>
                    <td>
                      <div class="action-buttons">
                        <button 
                          @click="viewStoryDetail(story)" 
                          class="btn btn-ghost btn-xs"
                          title="查看详情"
                        >
                          详情
                        </button>
                        <button 
                          v-if="story.review_status === 'pending'"
                          @click="approveStory(story.id)" 
                          class="btn btn-success btn-xs"
                        >
                          批准
                        </button>
                        <button 
                          v-if="story.review_status !== 'rejected'"
                          @click="rejectStory(story.id)" 
                          class="btn btn-warning btn-xs"
                        >
                          驳回
                        </button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 批量操作 -->
            <div v-if="selectedStories.length > 0" class="bulk-actions">
              <span class="selected-count">已选择 {{ selectedStories.length }} 个故事</span>
              <button @click="bulkApprove" class="btn btn-success btn-sm">
                <CheckCircle :size="16" />
                批量批准
              </button>
              <button @click="bulkReject" class="btn btn-warning btn-sm">
                <XCircle :size="16" />
                批量驳回
              </button>
            </div>
          </div>

          <!-- 故事详情弹窗 -->
          <div v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
            <div class="modal-content" @click.stop>
              <div class="modal-header">
                <h3>故事详情</h3>
                <button @click="closeDetailModal" class="close-btn">
                  <X :size="24" />
                </button>
              </div>
              <div class="modal-body" v-if="selectedStory">
                <div class="detail-section">
                  <label>标题：</label>
                  <p>{{ selectedStory.title }}</p>
                </div>
                <div class="detail-section">
                  <label>作者：</label>
                  <p>{{ selectedStory.author_name }}</p>
                </div>
                <div class="detail-section">
                  <label>分类：</label>
                  <p>{{ selectedStory.category }}</p>
                </div>
                <div class="detail-section">
                  <label>状态：</label>
                  <p>
                    <span class="status-badge" :class="selectedStory.status">
                      {{ getStatusText(selectedStory.status) }}
                    </span>
                  </p>
                </div>
                <div class="detail-section">
                  <label>审核状态：</label>
                  <p>
                    <span class="review-badge" :class="selectedStory.review_status">
                      {{ getReviewStatusText(selectedStory.review_status) }}
                    </span>
                  </p>
                </div>
                <div class="detail-section">
                  <label>内容：</label>
                  <p class="story-content">{{ selectedStory.content }}</p>
                </div>
                <div class="detail-section">
                  <label>审核备注：</label>
                  <textarea 
                    v-model="reviewNote" 
                    class="review-note-input"
                    placeholder="请输入审核备注（可选）"
                    rows="3"
                  ></textarea>
                </div>
              </div>
              <div class="modal-footer">
                <button 
                  v-if="selectedStory?.review_status === 'pending'"
                  @click="approveStoryWithNote" 
                  class="btn btn-success"
                >
                  批准
                </button>
                <button 
                  v-if="selectedStory?.review_status !== 'rejected'"
                  @click="rejectStoryWithNote" 
                  class="btn btn-warning"
                >
                  驳回
                </button>
                <button @click="closeDetailModal" class="btn btn-secondary">
                  关闭
                </button>
              </div>
            </div>
          </div>

          <!-- 系统设置 -->
          <div class="admin-section">
            <div class="section-header">
              <h2>系统设置</h2>
            </div>

            <div class="settings-grid">
              <div class="setting-item">
                <h4>清空所有数据</h4>
                <p>清空所有用户数据和故事（保留默认账号）</p>
                <button @click="clearAllData" class="btn btn-danger">
                  <Trash2 :size="16" />
                  清空数据
                </button>
              </div>

              <div class="setting-item">
                <h4>重置示例数据</h4>
                <p>重新加载示例故事数据</p>
                <button @click="resetSampleData" class="btn btn-primary">
                  <RefreshCw :size="16" />
                  重置数据
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useStoriesStore } from '../stores/stories'
import { useToast } from 'vue-toastification'
import { 
  Users, 
  BookOpen, 
  Eye, 
  Heart, 
  RefreshCw, 
  Trash2,
  CheckCircle,
  XCircle,
  X
} from 'lucide-vue-next'
import apiClient from '@/api/axios'
import { API_ENDPOINTS } from '@/api/config'
import ChartCard from '@/components/ChartCard.vue'

const authStore = useAuthStore()
const storiesStore = useStoriesStore()
const toast = useToast()

const users = ref([])
const stories = ref([])
const reviewFilter = ref('all')
const selectedStories = ref([])
const showDetailModal = ref(false)
const selectedStory = ref(null)
const reviewNote = ref('')
const analyticsData = ref(null)

// 统计数据
const totalUsers = computed(() => users.value.length)
const totalStories = computed(() => stories.value.length)
const totalViews = computed(() => stories.value.reduce((sum, story) => sum + (story.views || 0), 0))
const totalLikes = computed(() => stories.value.reduce((sum, story) => sum + (story.likes || 0), 0))

// 过滤后的故事列表
const filteredStories = computed(() => {
  if (reviewFilter.value === 'all') {
    return stories.value
  }
  return stories.value.filter(story => story.review_status === reviewFilter.value)
})

// 是否全选
const allSelected = computed(() => {
  return filteredStories.value.length > 0 && 
         selectedStories.value.length === filteredStories.value.length
})

// 加载用户数据
const loadUsers = async () => {
  try {
    const response = await apiClient.get(API_ENDPOINTS.USER_LIST)
    
    // 适配不同的响应格式
    let userList = []
    if (Array.isArray(response)) {
      userList = response
    } else if (response.results) {
      if (Array.isArray(response.results)) {
        userList = response.results
      } else if (response.results.data) {
        userList = Array.isArray(response.results.data) ? response.results.data : response.results.data.items || []
      }
    } else if (response.data) {
      userList = Array.isArray(response.data) ? response.data : response.data.items || []
    }
    
    users.value = userList.map(user => ({
      id: user.id,
      name: user.name || user.username,
      email: user.email,
      role: user.role,
      joinDate: user.join_date || user.joinDate || user.created_at,
      storiesCount: user.stories_count || user.storiesCount || 0
    }))
    
    console.log('加载用户成功:', users.value.length, '个')
  } catch (error) {
    console.error('加载用户失败:', error)
    // 如果API失败，显示当前登录用户
    if (authStore.currentUser) {
      users.value = [{
        id: authStore.currentUser.id,
        name: authStore.currentUser.name,
        email: authStore.currentUser.email,
        role: authStore.currentUser.role,
        joinDate: authStore.currentUser.join_date || authStore.currentUser.joinDate,
        storiesCount: authStore.currentUser.stories_count || authStore.currentUser.storiesCount || 0
      }]
    }
  }
}

// 加载故事数据
const loadStories = async () => {
  try {
    await storiesStore.loadStories({
      page: 1,
      page_size: 100
    })
    stories.value = [...storiesStore.stories]
  } catch (error) {
    console.error('加载故事失败:', error)
  }
}

// 刷新数据
const refreshUsers = async () => {
  await loadUsers()
  toast.success('用户数据已刷新')
}

const refreshStories = async () => {
  await loadStories()
  toast.success('故事数据已刷新')
}

// 切换用户角色
const toggleUserRole = (user) => {
  const newRole = user.role === 'admin' ? 'user' : 'admin'
  user.role = newRole
  
  // 更新localStorage
  const allUsers = JSON.parse(localStorage.getItem('users') || '[]')
  const userIndex = allUsers.findIndex(u => u.id === user.id)
  if (userIndex >= 0) {
    allUsers[userIndex].role = newRole
    localStorage.setItem('users', JSON.stringify(allUsers))
  }
  
  toast.success(`用户 ${user.name} 的角色已切换为 ${getRoleText(newRole)}`)
}

// 全选/取消全选
const toggleSelectAll = () => {
  if (allSelected.value) {
    selectedStories.value = []
  } else {
    selectedStories.value = filteredStories.value.map(s => s.id)
  }
}

// 查看故事详情
const viewStoryDetail = (story) => {
  selectedStory.value = story
  reviewNote.value = story.review_note || ''
  showDetailModal.value = true
}

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false
  selectedStory.value = null
  reviewNote.value = ''
}

// 批准故事
const approveStory = async (storyId) => {
  try {
    await apiClient.post(`/stories/${storyId}/approve`)
    toast.success('故事已批准')
    await loadStories()
  } catch (error) {
    toast.error('批准失败：' + (error.response?.data?.message || error.message))
  }
}

// 驳回故事
const rejectStory = async (storyId) => {
  if (confirm('确定要驳回这个故事吗？故事将变为草稿状态。')) {
    try {
      await apiClient.post(`/stories/${storyId}/reject`)
      toast.success('故事已驳回，状态已改为草稿')
      await loadStories()
    } catch (error) {
      toast.error('驳回失败：' + (error.response?.data?.message || error.message))
    }
  }
}

// 带备注批准故事
const approveStoryWithNote = async () => {
  if (!selectedStory.value) return
  try {
    await apiClient.post(`/stories/${selectedStory.value.id}/approve`, {
      review_note: reviewNote.value
    })
    toast.success('故事已批准')
    closeDetailModal()
    await loadStories()
  } catch (error) {
    toast.error('批准失败：' + (error.response?.data?.message || error.message))
  }
}

// 带备注驳回故事
const rejectStoryWithNote = async () => {
  if (!selectedStory.value) return
  if (confirm('确定要驳回这个故事吗？故事将变为草稿状态。')) {
    try {
      await apiClient.post(`/stories/${selectedStory.value.id}/reject`, {
        review_note: reviewNote.value
      })
      toast.success('故事已驳回，状态已改为草稿')
      closeDetailModal()
      await loadStories()
    } catch (error) {
      toast.error('驳回失败：' + (error.response?.data?.message || error.message))
    }
  }
}

// 批量批准
const bulkApprove = async () => {
  if (selectedStories.value.length === 0) return
  try {
    await Promise.all(
      selectedStories.value.map(id => apiClient.post(`/stories/${id}/approve`))
    )
    toast.success(`成功批准 ${selectedStories.value.length} 个故事`)
    selectedStories.value = []
    await loadStories()
  } catch (error) {
    toast.error('批量批准失败：' + (error.response?.data?.message || error.message))
  }
}

// 批量驳回
const bulkReject = async () => {
  if (selectedStories.value.length === 0) return
  if (confirm(`确定要驳回选中的 ${selectedStories.value.length} 个故事吗？它们将变为草稿状态。`)) {
    try {
      await Promise.all(
        selectedStories.value.map(id => apiClient.post(`/stories/${id}/reject`))
      )
      toast.success(`成功驳回 ${selectedStories.value.length} 个故事`)
      selectedStories.value = []
      await loadStories()
    } catch (error) {
      toast.error('批量驳回失败：' + (error.response?.data?.message || error.message))
    }
  }
}

// 删除故事（已禁用，保留代码以防需要）
const deleteStory = async (storyId) => {
  toast.warning('删除功能已禁用，请使用审核驳回功能')
  return
  // if (confirm('确定要删除这个故事吗？')) {
  //   try {
  //     await storiesStore.deleteStory(storyId)
  //     await loadStories()
  //   } catch (error) {
  //     toast.error('删除失败：' + (error.message || '请重试'))
  //   }
  // }
}

// 清空所有数据
const clearAllData = () => {
  if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
    // 保留默认用户
    const defaultUsers = [
      {
        id: 1001,
        name: '普通用户',
        email: 'user@test.com',
        password: '123456',
        avatar: '/default-avatar.png',
        bio: '我是一个普通用户，喜欢阅读和创作故事',
        joinDate: new Date().toISOString(),
        role: 'user',
        storiesCount: 0,
        likesReceived: 0
      },
      {
        id: 1002,
        name: '管理员',
        email: 'admin@test.com',
        password: '123456',
        avatar: '/default-avatar.png',
        bio: '我是系统管理员，负责维护平台运营',
        joinDate: new Date().toISOString(),
        role: 'admin',
        storiesCount: 0,
        likesReceived: 0
      }
    ]
    
    localStorage.setItem('users', JSON.stringify(defaultUsers))
    localStorage.setItem('stories', JSON.stringify([]))
    
    loadUsers()
    loadStories()
    toast.success('所有数据已清空')
  }
}

// 重置示例数据（重新从后端加载）
const resetSampleData = async () => {
  if (confirm('确定要重新加载数据吗？')) {
    try {
      await storiesStore.loadStories()
      await loadStories()
      toast.success('数据已重新加载')
    } catch (error) {
      toast.error('重新加载失败：' + error.message)
    }
  }
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 获取角色文本
const getRoleText = (role) => {
  const roleMap = {
    'user': '普通用户',
    'admin': '管理员',
    'creator': '创作者'
  }
  return roleMap[role] || role
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'draft': '草稿',
    'published': '已发布',
    'rejected': '已驳回'
  }
  return statusMap[status] || status
}

// 获取审核状态文本
const getReviewStatusText = (reviewStatus) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已驳回'
  }
  return statusMap[reviewStatus] || reviewStatus
}

// 加载分析数据
const loadAnalytics = async () => {
  try {
    const response = await apiClient.get('/stories/analytics')
    if (response.success || response.data) {
      analyticsData.value = response.data || response
      console.log('分析数据加载成功:', analyticsData.value)
    }
  } catch (error) {
    console.error('加载分析数据失败:', error)
    toast.error('加载分析数据失败')
  }
}

// 图表数据计算
const dailyStoriesChartData = computed(() => {
  if (!analyticsData.value?.daily_stories) return { labels: [], datasets: [] }
  return {
    labels: analyticsData.value.daily_stories.map(d => d.date),
    datasets: [{
      label: '故事数量',
      data: analyticsData.value.daily_stories.map(d => d.count),
      borderColor: 'rgb(102, 126, 234)',
      backgroundColor: 'rgba(102, 126, 234, 0.1)',
      tension: 0.4,
      fill: true
    }]
  }
})

const dailyUsersChartData = computed(() => {
  if (!analyticsData.value?.daily_users) return { labels: [], datasets: [] }
  return {
    labels: analyticsData.value.daily_users.map(d => d.date),
    datasets: [{
      label: '用户数量',
      data: analyticsData.value.daily_users.map(d => d.count),
      borderColor: 'rgb(34, 197, 94)',
      backgroundColor: 'rgba(34, 197, 94, 0.1)',
      tension: 0.4,
      fill: true
    }]
  }
})

const statusChartData = computed(() => {
  if (!analyticsData.value?.status_distribution) return { labels: [], datasets: [] }
  const dist = analyticsData.value.status_distribution
  return {
    labels: ['已发布', '草稿'],
    datasets: [{
      data: [dist.published || 0, dist.draft || 0],
      backgroundColor: [
        'rgba(34, 197, 94, 0.8)',
        'rgba(251, 191, 36, 0.8)'
      ],
      borderWidth: 2,
      borderColor: '#fff'
    }]
  }
})

const reviewChartData = computed(() => {
  if (!analyticsData.value?.review_distribution) return { labels: [], datasets: [] }
  const dist = analyticsData.value.review_distribution
  return {
    labels: ['待审核', '已通过', '已驳回'],
    datasets: [{
      data: [dist.pending || 0, dist.approved || 0, dist.rejected || 0],
      backgroundColor: [
        'rgba(251, 191, 36, 0.8)',
        'rgba(34, 197, 94, 0.8)',
        'rgba(239, 68, 68, 0.8)'
      ],
      borderWidth: 2,
      borderColor: '#fff'
    }]
  }
})

const categoryChartData = computed(() => {
  if (!analyticsData.value?.category_distribution) return { labels: [], datasets: [] }
  const dist = analyticsData.value.category_distribution
  return {
    labels: Object.keys(dist),
    datasets: [{
      label: '故事数量',
      data: Object.values(dist),
      backgroundColor: 'rgba(102, 126, 234, 0.8)',
      borderColor: 'rgb(102, 126, 234)',
      borderWidth: 1
    }]
  }
})

const authorsChartData = computed(() => {
  if (!analyticsData.value?.top_authors) return { labels: [], datasets: [] }
  return {
    labels: analyticsData.value.top_authors.map(a => a.name),
    datasets: [{
      label: '故事数量',
      data: analyticsData.value.top_authors.map(a => a.story_count),
      backgroundColor: 'rgba(168, 85, 247, 0.8)',
      borderColor: 'rgb(168, 85, 247)',
      borderWidth: 1
    }]
  }
})

onMounted(async () => {
  loadUsers()
  await loadStories()
  await loadAnalytics()
})
</script>

<style scoped>
.admin-panel {
  min-height: 100vh;
  padding: var(--spacing-2xl) 0;
}

.admin-header {
  text-align: center;
  margin-bottom: var(--spacing-3xl);
}

.page-title {
  font-size: var(--font-size-3xl);
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: var(--spacing-md);
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  font-size: var(--font-size-lg);
  color: var(--text-secondary);
  margin: 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: var(--spacing-xl);
  margin-bottom: var(--spacing-3xl);
}

.stat-card {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-xl);
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  transition: all var(--transition-fast);
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background: var(--gradient-primary);
  border-radius: var(--radius-lg);
  color: white;
}

.stat-info h3 {
  font-size: var(--font-size-2xl);
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-xs) 0;
}

.stat-info p {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin: 0;
}

.admin-sections {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-3xl);
}

.admin-section {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-xl);
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-tertiary);
}

.section-header h2 {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.data-table {
  overflow-x: auto;
}

.data-table table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: var(--spacing-md);
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.data-table th {
  background: var(--bg-tertiary);
  font-weight: 600;
  color: var(--text-primary);
  font-size: var(--font-size-sm);
}

.data-table td {
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

.story-title {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.role-badge,
.category-badge,
.status-badge {
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-xs);
  font-weight: 500;
}

.role-badge.admin {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.role-badge.user {
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
}

.category-badge {
  background: rgba(102, 126, 234, 0.1);
  color: var(--primary-color);
}

.status-badge.published {
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
}

.status-badge.draft {
  background: rgba(251, 191, 36, 0.1);
  color: #fbbf24;
}

.status-badge.rejected {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.review-badge {
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-xs);
  font-weight: 500;
}

.review-badge.pending {
  background: rgba(251, 191, 36, 0.1);
  color: #fbbf24;
}

.review-badge.approved {
  background: rgba(34, 197, 94, 0.1);
  color: #22c55e;
}

.review-badge.rejected {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.header-actions {
  display: flex;
  gap: var(--spacing-md);
  align-items: center;
}

.filter-select {
  padding: var(--spacing-xs) var(--spacing-md);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  background: var(--bg-primary);
  color: var(--text-primary);
  font-size: var(--font-size-sm);
  cursor: pointer;
}

.action-buttons {
  display: flex;
  gap: var(--spacing-xs);
  flex-wrap: wrap;
}

.bulk-actions {
  display: flex;
  gap: var(--spacing-md);
  align-items: center;
  padding: var(--spacing-lg);
  background: var(--bg-tertiary);
  border-top: 1px solid var(--border-color);
}

.selected-count {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin-right: auto;
}

.btn-success {
  background: #22c55e;
  color: white;
}

.btn-success:hover {
  background: #16a34a;
}

.btn-warning {
  background: #fbbf24;
  color: #78350f;
}

.btn-warning:hover {
  background: #f59e0b;
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.modal-content {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  max-width: 800px;
  width: 100%;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-xl);
  border-bottom: 1px solid var(--border-color);
}

.modal-header h3 {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: var(--spacing-xs);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-sm);
  transition: all var(--transition-fast);
}

.close-btn:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.modal-body {
  padding: var(--spacing-xl);
  overflow-y: auto;
  flex: 1;
}

.detail-section {
  margin-bottom: var(--spacing-lg);
}

.detail-section label {
  display: block;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
  font-size: var(--font-size-sm);
}

.detail-section p {
  color: var(--text-secondary);
  margin: 0;
  line-height: 1.6;
}

.story-content {
  max-height: 300px;
  overflow-y: auto;
  padding: var(--spacing-md);
  background: var(--bg-tertiary);
  border-radius: var(--radius-md);
  white-space: pre-wrap;
}

.review-note-input {
  width: 100%;
  padding: var(--spacing-md);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  background: var(--bg-primary);
  color: var(--text-primary);
  font-size: var(--font-size-sm);
  font-family: inherit;
  resize: vertical;
}

.modal-footer {
  display: flex;
  gap: var(--spacing-md);
  justify-content: flex-end;
  padding: var(--spacing-xl);
  border-top: 1px solid var(--border-color);
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: var(--spacing-xl);
  padding: var(--spacing-xl);
}

.setting-item {
  padding: var(--spacing-lg);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  background: var(--bg-primary);
}

.setting-item h4 {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
}

.setting-item p {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin: 0 0 var(--spacing-lg) 0;
}

/* Analytics Section */
.analytics-section {
  margin-bottom: var(--spacing-3xl);
}

.section-header-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-2xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 2px solid var(--border-color);
}

.section-header-main h2 {
  font-size: var(--font-size-2xl);
  font-weight: 700;
  color: var(--text-primary);
  margin: 0;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: var(--spacing-xl);
  margin-bottom: var(--spacing-2xl);
}

.chart-wide {
  grid-column: span 2;
}

.top-stories-section {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-xl);
  margin-top: var(--spacing-2xl);
}

.top-stories-section h3 {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-lg) 0;
}

.rank-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  font-weight: 700;
  font-size: var(--font-size-sm);
}

.rank-badge.rank-1 {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #78350f;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
}

.rank-badge.rank-2 {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  color: #374151;
  box-shadow: 0 2px 8px rgba(192, 192, 192, 0.4);
}

.rank-badge.rank-3 {
  background: linear-gradient(135deg, #cd7f32, #e9a96a);
  color: #78350f;
  box-shadow: 0 2px 8px rgba(205, 127, 50, 0.4);
}

.rank-badge.rank-4,
.rank-badge.rank-5 {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  border: 1px solid var(--border-color);
}

.metric-badge {
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-sm);
  font-weight: 600;
}

.metric-badge.views {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
}

.metric-badge.likes {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

/* Mobile Styles */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .section-header {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }
  
  .settings-grid {
    grid-template-columns: 1fr;
  }

  .charts-grid {
    grid-template-columns: 1fr;
  }

  .chart-wide {
    grid-column: span 1;
  }

  .section-header-main {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }
}
</style>
